package org.ehe.business.workstation.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.ehe.business.workstation.domain.Workstation;
import org.ehe.business.workstation.mapper.WorkstationMapper;
import org.ehe.common.core.exception.ServiceException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 工位编码生成服务
 * 编码规则: 03.工位code.设备号
 *
 * @author zhangnn
 * @date 2025-10-23
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WorkstationCodeService {

    private final WorkstationMapper workstationMapper;

    /**
     * 固定前缀(非标件库)
     */
    private static final String PREFIX = "03";

    /**
     * 分隔符
     */
    private static final String SEPARATOR = ".";

    /**
     * 设备号长度
     */
    private static final int DEVICE_CODE_LENGTH = 6;

    /**
     * 生成工位编码
     *
     * @param workstationCode 工位编号(4位数字)
     * @param deviceName      设备名称(用于预览)
     * @return 编码生成结果
     */
    public CodeGenerateResult generateCode(String workstationCode, String deviceName) {
        try {
            // 1. 校验工位编号
            if (StrUtil.isBlank(workstationCode)) {
                return CodeGenerateResult.fail("工位编号不能为空");
            }

            if (!workstationCode.matches("\\d{3}")) {
                return CodeGenerateResult.fail("工位编号必须为3位数字");
            }

            // 2. 查询该工位下已有的设备数量
            int deviceCount = getDeviceCountByWorkstation(workstationCode);

            // 3. 生成新的设备序号(从1开始)
            int nextDeviceNo = deviceCount + 1;
            String deviceCode = String.format("%0" + DEVICE_CODE_LENGTH + "d", nextDeviceNo);

            // 4. 拼接完整编码
            String fullCode = PREFIX + SEPARATOR + workstationCode + SEPARATOR + deviceCode;

            // 5. 构建返回结果
            return CodeGenerateResult.success(
                    workstationCode,
                    deviceCode,
                    fullCode,
                    deviceName,
                    nextDeviceNo);

        } catch (Exception e) {
            log.error("生成工位编码失败", e);
            return CodeGenerateResult.fail("生成编码失败: " + e.getMessage());
        }
    }

    /**
     * 查询工位下的设备数量
     *
     * @param workstationCode 工位编号
     * @return 设备数量
     */
    private int getDeviceCountByWorkstation(String workstationCode) {
        // TODO: 这里需要查询设备表,暂时返回0
        // 如果有设备表,应该这样查询:
        // LambdaQueryWrapper<Equipment> wrapper = new LambdaQueryWrapper<>();
        // wrapper.eq(Equipment::getWorkstationCode, workstationCode);
        // return equipmentMapper.selectCount(wrapper).intValue();

        return 0;
    }

    /**
     * 校验编码是否已存在
     *
     * @param fullCode 完整编码
     * @return 是否已存在
     */
    public boolean isCodeExists(String fullCode) {
        // TODO: 查询设备表检查编码是否存在
        return false;
    }

    /**
     * 解析完整编码
     *
     * @param fullCode 完整编码(如: 03.0001.000001)
     * @return 解析结果
     */
    public CodeParseResult parseCode(String fullCode) {
        if (StrUtil.isBlank(fullCode)) {
            return null;
        }

        String[] parts = fullCode.split("\\.");
        if (parts.length != 3) {
            return null;
        }

        CodeParseResult result = new CodeParseResult();
        result.setPrefix(parts[0]);
        result.setWorkstationCode(parts[1]);
        result.setDeviceCode(parts[2]);
        result.setFullCode(fullCode);

        return result;
    }

    /**
     * 编码生成结果
     */
    public static class CodeGenerateResult {
        private boolean success;
        private String message;
        private String workstationCode;
        private String deviceCode;
        private String fullCode;
        private String deviceName;
        private String fullName;
        private int sequenceNo;

        public static CodeGenerateResult success(String workstationCode, String deviceCode,
                String fullCode, String deviceName, int sequenceNo) {
            CodeGenerateResult result = new CodeGenerateResult();
            result.success = true;
            result.message = "编码生成成功";
            result.workstationCode = workstationCode;
            result.deviceCode = deviceCode;
            result.fullCode = fullCode;
            result.deviceName = deviceName;
            result.fullName = "非标件库_" + deviceName;
            result.sequenceNo = sequenceNo;
            return result;
        }

        public static CodeGenerateResult fail(String message) {
            CodeGenerateResult result = new CodeGenerateResult();
            result.success = false;
            result.message = message;
            return result;
        }

        // Getters
        public boolean isSuccess() {
            return success;
        }

        public String getMessage() {
            return message;
        }

        public String getWorkstationCode() {
            return workstationCode;
        }

        public String getDeviceCode() {
            return deviceCode;
        }

        public String getFullCode() {
            return fullCode;
        }

        public String getDeviceName() {
            return deviceName;
        }

        public String getFullName() {
            return fullName;
        }

        public int getSequenceNo() {
            return sequenceNo;
        }
    }

    /**
     * 编码解析结果
     */
    public static class CodeParseResult {
        private String prefix;
        private String workstationCode;
        private String deviceCode;
        private String fullCode;

        // Getters and Setters
        public String getPrefix() {
            return prefix;
        }

        public void setPrefix(String prefix) {
            this.prefix = prefix;
        }

        public String getWorkstationCode() {
            return workstationCode;
        }

        public void setWorkstationCode(String workstationCode) {
            this.workstationCode = workstationCode;
        }

        public String getDeviceCode() {
            return deviceCode;
        }

        public void setDeviceCode(String deviceCode) {
            this.deviceCode = deviceCode;
        }

        public String getFullCode() {
            return fullCode;
        }

        public void setFullCode(String fullCode) {
            this.fullCode = fullCode;
        }
    }
}
